import { Injectable, OnModuleInit, Logger } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';
import { DatabaseInitializerService } from './shared/database-initializer.service';

@Injectable()
export class SeederService implements OnModuleInit {
  private readonly logger = new Logger(SeederService.name);

  private readonly seedSqlFilePath = path.join(
    __dirname,
    '/../../db/crm-database.sql',
  );

  constructor(
    private readonly dbInitializer: DatabaseInitializerService, // ✅ 注入共享服务
  ) {}

  async onModuleInit() {
    try {
      // 1. 读取 SQL 文件内容
      this.logger.log(`📂 Reading seed SQL file from: ${this.seedSqlFilePath}`);
      const sql = fs.readFileSync(this.seedSqlFilePath, 'utf8');

      this.logger.log('🌱 Starting database seeding...');

      // 2. 调用共享服务执行 SQL（可以是建表、插入数据等任意 SQL）
      await this.dbInitializer.executeSql(sql);

      this.logger.log('✅ Database seeded successfully ✅');
    } catch (error) {
      this.logger.error('❌ Failed to seed database:', error);
      throw error; // 可根据需要处理异常，比如终止应用启动
    }
  }
}
